<?php

namespace App\Http\Middleware;

use App\Services\ValidatorService;
use Closure;
use Illuminate\Http\Request;

class RequestApiCheck
{
    private function checkRequestParams($request)
    {
        $path = $request->path();
        $rules = config("validatas.{$path}");
        if (empty($rules)) {
            return true;
        }

        $ret = ValidatorService::getInstance()->validate($request->all(), $rules);
        if (!$ret) {
            return false;
        }

        return true;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        // 校验请求参数
        if (!$this->checkRequestParams($request)) {
            return yqerr(102);
        }

        return $next($request);
    }
}
